package s3;

import cn.hutool.core.img.Img;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Locale;

/**
 * @author: Wu ZiLin
 * @create: 2023-09-06 16:14
 * @description: 图片格式工具类
 **/
public class ImageWUtil {
    private ImageWUtil() {
    }

    /**
     * 获取Img流和目标地址转换jpg,返回InputStream
     */
    public static InputStream imageConversion2ImgStream(InputStream inputStream, String bufferType) {
        try {
            BufferedImage buffer = ImageIO.read(inputStream);
            return bufferedConversion2ImgStream(buffer, bufferType);
        } catch (IOException e) {
            // IO流读取文件失败
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取图片流转换Img,并进行裁剪,返回InputStream
     */
    public static InputStream bufferedConversion2ImgStream(BufferedImage buffer, String bufferType) {
        try (ByteArrayOutputStream img = new ByteArrayOutputStream()) {
            Rectangle r = "pdf".equals(bufferType) ? cropPdfPicture(0, 0, buffer.getWidth(), buffer.getHeight()) :
                    cropPicture(0, 0, buffer.getWidth(), buffer.getHeight());
            Img.from(buffer)
                    .setPositionBaseCentre(false)
                    .cut(r)
                    .setTargetImageType("jpg")
                    .setQuality(1)
                    .write(img);
            return new ByteArrayInputStream(img.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取图片流和目标地址转换ProgressiveJPEG,返回InputStream
     */
    public static InputStream bufferedConversion2ProgressiveJPEGStream(InputStream inputStream) {
        BufferedImage bufferedImage;
        InputStream inputTempFile = null;
        ImageOutputStream output = null;
        ImageWriter writer = null;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream(37628)) {
            bufferedImage = ImageIO.read(inputStream);
            Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("jpeg");
            while (it.hasNext()) {
                writer = it.next();
                break;
            }
            if (writer != null) {
                ImageWriteParam params = writer.getDefaultWriteParam();
                params.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
                // params.setCompressionQuality(0.8f);
                output = ImageIO.createImageOutputStream(baos);
                writer.setOutput(output);
                writer.write(null, new IIOImage(bufferedImage, null, null), params);
                output.flush();
                inputTempFile = new ByteArrayInputStream(baos.toByteArray());
            }
            return inputTempFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                output.close();
                writer.dispose();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 判断图片真实格式
     *
     * @param inputStream
     * @return
     */
    public static String imgType(InputStream inputStream) {
        try {
            // 读取文件前几位
            byte[] fileHeader = new byte[4];
            inputStream.read(fileHeader, 0, fileHeader.length);
            inputStream.close();
            // 转为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : fileHeader) {
                String hex = Integer.toHexString(b & 0xff);
                sb.append(hex.length() == 2 ? hex : ("0" + hex));
            }
            String header = sb.toString().toUpperCase(Locale.ROOT);
            if (header.contains("FFD8FF")) {
                return "jpg";
            } else if (header.contains("89504E47")) {
                return "png";
            } else if (header.contains("47494638")) {
                return "gif";
            } else if (header.contains("424D")) {
                return "bmp";
            } else if (header.contains("52494646")) {
                return "webp";
            } else if (header.contains("49492A00")) {
                return "tif";
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取图片宽高裁剪图片大小
     */
    private static Rectangle cropPicture(int x, int y, int width, int height) {
        if (width > height) {
            x = (width - height) / 2;
            width = width - 2 * x;
        } else {
            y = (height - width) / 2;
            height = height - 2 * y;
        }
        width = Math.min(width, height);
        return new Rectangle(x, y, width, width);
    }

    /**
     * 获取pdf图片宽高裁剪图片大小
     */
    private static Rectangle cropPdfPicture(int x, int y, int width, int height) {
        if (width > height) {
            x = (width - height) / 2;
            width = width - 2 * x;
        }
        width = Math.min(width, height);
        return new Rectangle(x, y, width, width);
    }

}
